/**
 * Rule Factor
 * 规则因子
 */

import { isArray, isObject, isString } from 'fc-cli-core'
import { DataType } from './FCRuleTableConstant'
import FCRuleFactorValue from './FCRuleFactorValue'

class FCRuleFactor {
  key
  dataType
  code
  title
  options

  get isEnum() {
    return isArray(this.options) && this.options.length > 0
  }
  get isLink() {
    return !!this.linkProps
  }

  /* lifecycle methods */

  constructor({ key, code, title, options, dataType = DataType.string, mergeData = [], render, parser, linkProps } = {}) {
    this.key = key
    this.code = code
    this.title = title
    this.options = this.buildOptions(options)
    this.dataType = dataType
    this.render = render
    this.parser = parser
    this.linkProps = linkProps
    this.mergeData = mergeData
  }

  buildOptions(options) {
    if (!isArray(options)) {
      return []
    }

    return options.map((optionData) => this.buildFactorValue(optionData))
  }

  // 设置合并数据
  setMergeData(mergeData) {
    this.mergeData = [...this.mergeData, mergeData]
  }

  /* public methods */

  setTitle(title) {
    this.title = title

    // todo: 通知界面刷新
    // this.table.postNotification('factor.title-' + title)
  }

  /* private methods */

  buildFactorValue({ value, label } = {}) {
    return new FCRuleFactorValue({
      key: this.createNewValueKey(),
      value,
      label,
      factor: this,
    })
  }

  // 生成 value.key
  #valueIndex = 1
  createNewValueKey() {
    return `${this.key}-v:${this.#valueIndex++}`
  }
}

export default FCRuleFactor
